package com.joelbitar.switchctrl;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class settings extends ListActivity {
	public static final String PUBLIC_STATIC_STRING_IDENTIFIER = "details_result";
	
	private static final int MENU_ADD = 0;
	private static final int MENU_UPDATE = 1;
	
	private ServerListAdapter serveradapter;
	private ArrayList<Server> servers = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings);
        
       // Setting the serverAdapter
        servers = new ArrayList<Server>();
        
        serveradapter = new ServerListAdapter(this, R.layout.settings_servers_row, servers);
        
        setListAdapter(serveradapter);
        
        ListView listview = getListView();
        
        // Find the listView and add the setOnItemClickListener on it.
        // listView.setOnItemClickListener(new OnItemClickListener);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> a, View v, int position, long id) {
              Log.i("onitemclick", "On item click");
              
              Server server = (Server) v.getTag();
              
              Log.i("server", server.getName());
              
              startEditActivity(server);
              
           }
        });
        
        
        listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> a, View v, int position, long id) {
               Log.i("onitemclick", "On item click");
               
               Server server = (Server) v.getTag();
               
               Log.i("server", server.getName());
               
               showServerDialog(server);
               
               return true;
            }
         });
        
        
        /*
         * Some tests with spinners
         * */
        

        Preferences prefs = switchctrl.preferences;

        Preference vibrationLength = prefs.get(Preferences.VIBRATE_LENGTH);
        
        Spinner vibrationSpinner = (Spinner) findViewById(R.id.vibration_length_spinner);
        ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.settings_vibrate_length_values, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        vibrationSpinner.setAdapter(adapter);
        vibrationSpinner.setSelection(vibrationLength.getIndexOfStoredValue());
        
        vibrationSpinner.setOnItemSelectedListener(new GenericOnItemSelectedListener(vibrationLength));
        /*
        // If use real requests
        Preference realRequests = prefs.get(Preferences.REAL_REQUESTS);
        
        CheckBox realRequestsCheckbox = (CheckBox) findViewById(R.id.use_real_requests);
        realRequestsCheckbox.setChecked(realRequests.getStoredValueBoolean()); 
        
        realRequestsCheckbox.setOnCheckedChangeListener(new GenericOnCheckedChangeListener(realRequests));
        */
        
        updateServerList();
	}

	public void onResume(Bundle savedInstance)
	{
		Log.i("test", "Test");
	}

	public void onStart(Bundle savedInstance)
	{
		Log.i("test", "testst");
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MENU_ADD, 0, getString(R.string.menu_settings_servers_add)).setIcon(android.R.drawable.ic_menu_add);
		menu.add(0, MENU_UPDATE, 0, getString(R.string.menu_settings_servers_update)).setIcon(android.R.drawable.ic_menu_rotate);
		return true;
	}
   
	/* Handles item selections */
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
		    case MENU_ADD:
		    	launchAddServerActivity();
		        return true;
		    case MENU_UPDATE:
		    	updateServerList();
		        return true;
	    }
	    return false;
	}
	
	public boolean launchAddServerActivity() {
		
		Intent myIntent = new Intent();
		//myIntent.setClassName("com.android.samples", "com.android.samples.Animation1");
		myIntent.setClassName("com.joelbitar.switchctrl", "com.joelbitar.switchctrl.serverdetails");
		myIntent.putExtra(serverdetails.INTENT_ADD, true);
		startActivityForResult(myIntent, 0);
		
		return true;
	}

	public void startEditActivity(Server server) {

		Intent intent = new Intent();
		
		intent.setClassName("com.joelbitar.switchctrl", "com.joelbitar.switchctrl.serverdetails");
		intent.putExtra(serverdetails.INTENT_EDIT, true);
		
		Log.w("starteditactivity", "Starting the edit activity");
		Log.i("serverid", "" + server.getId());
		
		intent.putExtra(serverdetails.INTENT_EDIT_SERVER_ID, server.getId());

		startActivityForResult(intent, 0);
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {   
		super.onActivityResult(requestCode, resultCode, data); 
		
		Log.i("onactivityresult", "" + resultCode);
		
		this.updateServerList();
	}

	public boolean updateServerList() {
        ServerDbAdapter serverdbadapter = new ServerDbAdapter(this);
        
        Cursor allServersCursor = serverdbadapter.getAllServers();
        
        servers.clear();
        
        if(allServersCursor.moveToFirst())
        {
        	do {
        		String name = allServersCursor.getString(ServerDbAdapter.NAME_COLUMN);
        		long id = allServersCursor.getLong(ServerDbAdapter.ID_COLUMN);
        		String url = allServersCursor.getString(ServerDbAdapter.URL_COLUMN);
        		String username = allServersCursor.getString(ServerDbAdapter.USERNAME_COLUMN);
        		String password = allServersCursor.getString(ServerDbAdapter.PASSWORD_COLUMN);
        		
        		Server server = new Server();
        		server.setId(id);
        		server.setName(name);
        		server.setHosturl(url);
        		server.setUsername(username);
        		server.setPassword(password);
        		
        		servers.add(server);
        		Log.i("Name", name);
        		
        	} while (allServersCursor.moveToNext());
        }
        else
        {
        	Log.i("SERVERS", "NO servers found");
        }
		
        this.serveradapter.notifyDataSetChanged();
        
		return true;
	}
	

	public void showServerDialog(final Server server)
	{
		
        final Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.settings_server_dialog);
        dialog.setTitle(R.string.settings_server_dialog);
        dialog.setCancelable(true);

        Button edit = (Button) dialog.findViewById(R.id.edit);
        Button delete = (Button) dialog.findViewById(R.id.delete);
        Button abort = (Button) dialog.findViewById(R.id.abort);
        
        edit.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.hide();
				startEditActivity(server);
			}
		});

        abort.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.hide();
			}
		});
        
        delete.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				ServerDbAdapter dbAdapter = new ServerDbAdapter(getApplicationContext()); 
				dbAdapter.deleteServer(server);
				updateServerList();
				dialog.hide();
			}
		});
        
        // Show the dialog
        dialog.show();
	}
	
	public class GenericOnItemSelectedListener implements OnItemSelectedListener {
		
		private Preference preference;
		
		public GenericOnItemSelectedListener(Preference preference)
		{
			this.preference = preference;
		}
		
	    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
	    	
			Object item = parent.getItemAtPosition(pos);
			
			Preferences prefs = new Preferences(getBaseContext());
			
	    	Log.i("Selected", "position: " + pos);
	    	Log.i("selecte", "value: " + item.toString());
	    	Log.i("preference", this.preference.getName());
	    	Log.i("Old value", "" + this.preference.getValue());
	    	Log.i("Old stored value", "" + this.preference.getStoredValue());
	    	
	    	switch(this.preference.getId())
	    	{
	    	case Preferences.VIBRATE_LENGTH:
	    		
	    		int value = (Integer) this.preference.getSpinnerValues().get(pos);
	    		
	    		this.preference.setValue((Object) value);
	    		
	    		prefs.save(this.preference);
	    		
	    		break;
	    	}

	    	Log.i("New value", "" + this.preference.getValue());
	    	Log.i("New stored value", "" + this.preference.getStoredValue());
	    	
	    	//EditText e = (EditText) view;
	    	
	    	//Log.i("value", e.getText().toString());
	    	
	    }

	    public void onNothingSelected(AdapterView parent) {
	      // Do nothing.
	    }
	}
	
	public class GenericOnCheckedChangeListener implements OnCheckedChangeListener {
		private Preference preference;
		
		public GenericOnCheckedChangeListener(Preference preference)
		{
			this.preference = preference;
			
		}

		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

			Preferences prefs = new Preferences(getBaseContext());
			this.preference.setValue((isChecked == true) ? 1 : 0);
			
			prefs.save(preference);
		}
	}
	
	public void testVibrationLength(View view)
	{
		Log.v("test", "hejs");
	}
}
